import {defaultModel} from '../typs/flow';
import '../flow-style.css';
import {isEmpty} from '../../../utils';
import {createService} from '@/request/service.js';
import FlowSupport from '../FlowSupport.js';

export default {
  data() {
    return {
      graph: undefined,
      showMiniMap: false,
      supportService: undefined
    };
  },
  createFlowModel(vue) {
    if (!isEmpty(vue.graph)) {
      this.reRenderFlowModel(vue);
      return;
    }
    this.resolveDefaultModel(vue);
    this.createGraph(vue);
    this.reRenderFlowModel(vue);
  },
  reRenderFlowModel(vue) {
    this.supportService.reRenderFlowModel(this.getModel(vue));
  },
  resolveDefaultModel(vue) {
    if (isEmpty(vue.value)) {
      let v
      vue.$emit('change', v = JSON.stringify(this.getDefaultModel(vue)));
      vue && vue.change && vue.change(v);
    }
  },
  createGraph(vue) {
    let {graph, support} = FlowSupport.createGraph(vue.$refs.flowContainer, this.getCtx(vue));
    this.graph = graph;
    this.supportService = support;
  },
  getCtx(vue) {
    return {
      getModel: () => this.getModel(vue),
      setModel: model => vue.$emit('change', model),
      slots: {
        ...vue.$slots,
        ...vue.$scopedSlots,
      },
      miniMap: vue.$refs.flowMiniMap,
      toolBarContainer: vue.$refs.toolBarContainer,
      ...vue.$props,
      service: vue.service ? vue.service : (vue.service = createService(vue.request)),
      flowPathRecord: vue.flowPathRecord,
    };
  },
  getModel(vue) {
    if (isEmpty(vue.value)) {
      return JSON.parse(JSON.stringify(this.getDefaultModel(vue)));
    }
    return JSON.parse(vue.value);
  },
  getDefaultModel(vue) {
    return vue.defaultMode = vue.defaultMode ? vue.defaultMode : defaultModel();
  }
}
